﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WordServices.HttpService;

// The Content Dialog item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace WordsOfLove.ForumPages
{
	public sealed partial class RegisterDialog : ContentDialog
	{
		public RegisterDialog()
		{
			this.InitializeComponent();
			IsPrimaryButtonEnabled = false;
		}

		private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
		{
			if(PasswordBox.Password != ConfirmBox.Password)
			{
				await new MessageDialog("两次输入的密码不一致").ShowAsync();
				args.Cancel = true;
				return;
			}
			try
			{
				HttpUtils utils = HttpUtilsFactory.Utils;
				User user = utils.SendPostAndReturnJsonMessage<User>("api/User/CreateUser", new User
				{
					Id = -1,
					UserName = UserNameBox.Text,
					Password = Md5Encoder.Encode(PasswordBox.Password)
				});
				CurrentUserFactory.CurrentUser = user;
			}
			catch //(Exception ex)
			{
				await new MessageDialog("服务器错误").ShowAsync();
				args.Cancel = true;
			}
		}

		private void CheckUserNameBtn_Click(object sender, RoutedEventArgs e)
		{
			if (UserNameBox.Text.Length > 40)
			{
				HintTxt.Text = "该用户名过长，无法使用。";
				IsPrimaryButtonEnabled = false;
				return;
			}
			else if(UserNameBox.Text.Length < 4)
			{
				HintTxt.Text = "该用户名过短，无法使用。";
				IsPrimaryButtonEnabled = false;
				return;
			}
			try
			{
				HttpUtils utils = HttpUtilsFactory.Utils;
				bool result = utils.SendGetJsonMessage<bool>($"api/User/CheckUserName?username={UserNameBox.Text}");
				if (result)
				{
					HintTxt.Text = "该用户名可以使用。";
					IsPrimaryButtonEnabled = true;
				}
				else
				{
					HintTxt.Text = "该用户名已被占用，无法使用。";
					IsPrimaryButtonEnabled = false;
				}
			}
			catch //(Exception ex)
			{
				new MessageDialog("服务器错误").ShowAsync();
				IsPrimaryButtonEnabled = false;
			}
		}

		private void UserNameBox_TextChanged(object sender, TextChangedEventArgs e)
		{
			IsPrimaryButtonEnabled = false;
			HintTxt.Text = "尚未检查用户名是否可用。";
		}
	}
}
